package com.ubi.core.framework;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import com.mangofactory.swagger.readers.operation.RequestMappingReader;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

/**
 * 标题、简要说明. <br>
 * 类详细说明.
 * <p/>
 * Copyright: Copyright (c) 2016年06月14日 9:52
 * <p/>
 * Company:
 * <p/>
 *
 * @author Kent
 * @version 1.0.0
 */
@EnableSwagger
public class DefaultSwaggerConfig {

    @Autowired
    private SpringSwaggerConfig springSwaggerConfig;

    @Bean
    public SwaggerSpringMvcPlugin swaggerSpringMvcPlugin() {
        SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(this.springSwaggerConfig);
        swaggerSpringMvcPlugin.apiInfo(this.buildApiDocSiteInfo());
        swaggerSpringMvcPlugin.customAnnotationReaders(this.getSwaggerRequestMappingReaders());
        swaggerSpringMvcPlugin.includePatterns(this.getSwaggerScanPatterns());
        return swaggerSpringMvcPlugin;
    }

    protected String[] getSwaggerScanPatterns() {
        List<String> apiPathPatterns = this.apiPathPatterns();
        if (CollectionUtils.isEmpty(apiPathPatterns)) {
            return this.getDefaultPatterns();
        }
        return apiPathPatterns.toArray(new String[apiPathPatterns.size()]);
    }

    protected String[] getDefaultPatterns() {
        if (isExcludeCenterAPI()) {
            return new String[] { "((?!/api/)|(?!/monitor/)).*?" };
        } else {
            return new String[] { "(?!/monitor/).*?" };
        }
    }

    /**
     * 是否排除中心层接口(以/api/开头)
     */
    protected boolean isExcludeCenterAPI() {
        return true;
    }

    /**
     * 自定义要扫描的接口路径请复写此方法, 默认 ".*?" 或者 "(?!/api/).*?"
     * (?!/api/).*?  为排除中心层含/api/路径的正则
     * .*?  为swagger默认配置，表示默认匹配所有
     */
    protected List<String> apiPathPatterns() {
        return new ArrayList<>();
    }

    protected List<RequestMappingReader> getSwaggerRequestMappingReaders() {
        return new ArrayList<>();
    }

    /**
     * 设置swagger站点信息
     */
    protected ApiInfo buildApiDocSiteInfo() {

        String classPath = this.getClass().getResource("/").getPath().replace("/target/classes/", "");
        String projectName = classPath.substring(classPath.lastIndexOf('/') + 1, classPath.length());
        projectName = StringUtils.isBlank(projectName) ? "Duoxue Java Service" : projectName;
        String description = projectName.concat("API Document");

        return new ApiInfo(projectName, description, "", "", "", "");
    }

}
